package com.cloudbroker.bcs.platform.ltb.common.ext.interceptor;

import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.util.DESUtil;
import com.cloudbroker.bcs.platform.ltb.common.constant.IFSConstant;
import com.cloudbroker.bcs.platform.ltb.common.ext.annotation.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dengwei06015 on 2016/1/19.
 */
public class ParamsValidateInterceptor extends HandlerInterceptorAdapter {
    private static Logger log = LoggerFactory.getLogger(ParamsValidateInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            NotEmpty annotation = method.getAnnotation(NotEmpty.class);
            if (annotation != null) {
                String fields = annotation.field();
                String message = annotation.message();
                if (!StringUtils.isEmpty(fields)) {
                    for (String field : fields.split(",")) {
                        if (StringUtils.isEmpty(request.getParameter(field))) {
                            returnParamtersCheck(request, response, field, message);
                            return false;
                        }
                        //校验user_token
                        if("user_token".equals(field)){
                            String user_token  = request.getParameter("user_token");
                            try {
                                DESUtil.decode(user_token);
                            }catch (Exception e){
                                log.error("校验user_token出错");
                                returnUserTokenCheck(request, response);
                                return false;
                            }
                        }
                    }
                }
            }
        }
        // 没有注解通过拦截
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {
    }


    private void returnParamtersCheck(HttpServletRequest request, HttpServletResponse response, String field, String mesage) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("error_no", IFSConstant.ERR_SYS_NOTEMPTY);
        resMap.put("error_info", "必填域(" + field + ")不能为空");
        if (!StringUtils.isEmpty(mesage)) {
            resMap.put("error_info", mesage);
        }
        output( request,  response, resMap);
    }

    private void returnUserTokenCheck(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("error_no", IFSConstant.ERR_SYS_TOKEN);
        resMap.put("error_info", "user_token不合法");
        output( request,  response, resMap);
    }

    private void output(HttpServletRequest request, HttpServletResponse response,Map<String, Object> resMap){
        try {
            OutputStream out = response.getOutputStream();
            String jsonpcallback = request.getParameter("jsonpcallback");
            if (!StringUtils.isEmpty(jsonpcallback)) {
                String text = jsonpcallback + "(" + JSON.toJSONString(resMap) + ")";
                log.info("拦截返回===>"+text);
                out.write(text.getBytes("UTF-8"));
            } else {
                log.info("拦截返回===>"+JSON.toJSONString(resMap));
                out.write(JSON.toJSONString(resMap).getBytes("UTF-8"));
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
